//package com.xyz.filter;
//
//import com.xyz.entity.R;
//import com.xyz.entity.SecurityUser;
//import com.xyz.entity.User;
//import com.xyz.utils.ResponseUtil;
//import com.xyz.security.TokenManager;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import jakarta.servlet.ServletInputStream;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.security.authentication.AuthenticationManager;
//import org.springframework.security.authentication.AuthenticationServiceException;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.Authentication;
//import org.springframework.security.core.AuthenticationException;
//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
//
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.stream.Collectors;
//
///**
// * <p>
// * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
// * </p>
// *
// * @author zsr
// * @since 2021-06-27
// */
//public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
//
//    private AuthenticationManager authenticationManager;//spring security
//    private TokenManager tokenManager;
//    private RedisTemplate redisTemplate;
//
//    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
//        super();
//        this.authenticationManager = authenticationManager;
//        this.tokenManager = tokenManager;
//        this.redisTemplate = redisTemplate;
//        this.setPostOnly(false);
//        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST"));
//        this.setAuthenticationManager(authenticationManager); // 重要：设置认证管理器
//    }
//
//    /**
//     * [重写]1.根据请求获取 用户名和密码进行身份验证
//     * @param req
//     * @param res
//     * @return
//     * @throws AuthenticationException
//     */
//    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
//            throws AuthenticationException {
//        try {
//            logger.info("开始认证尝试...");
//
//            // 使用安全的方式读取请求体
//            String requestBody = getRequestBody(req);
//            logger.info("请求体内容: " + requestBody);
//
//            if (requestBody == null || requestBody.isEmpty()) {
//                logger.error("请求体为空");
//                throw new AuthenticationServiceException("请求体为空");
//            }
//
//            User user = new ObjectMapper().readValue(requestBody, User.class);
//            logger.info("解析的用户名: " + user.getUsername());
//
//            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
//                    user.getUsername(), user.getPassword(), new ArrayList<>()
//            );
//
//            // 设置详情，以便在认证成功后可以获取到
//            authRequest.setDetails(new WebAuthenticationDetailsSource().buildDetails(req));
//
//            Authentication authentication = authenticationManager.authenticate(authRequest);
//            logger.info("认证成功: " + authentication.isAuthenticated());
//
//            return authentication;
//
//        } catch (IOException e) {
//            logger.error("IO异常: " + e.getMessage(), e);
//            throw new AuthenticationServiceException("认证失败: IO异常", e);
//        } catch (Exception e) {
//            logger.error("认证过程中发生异常: " + e.getMessage(), e);
//            throw new AuthenticationServiceException("认证失败: " + e.getMessage(), e);
//        }
//    }
//
//    private String getRequestBody(HttpServletRequest request) {
//        try {
//            return request.getReader().lines().collect(Collectors.joining());
//        } catch (IOException e) {
//            logger.warn("无法从reader读取请求体，尝试其他方式");
//            try {
//                // 尝试从输入流读取
//                ServletInputStream inputStream = request.getInputStream();
//                ByteArrayOutputStream result = new ByteArrayOutputStream();
//                byte[] buffer = new byte[1024];
//                int length;
//                while ((length = inputStream.read(buffer)) != -1) {
//                    result.write(buffer, 0, length);
//                }
//                return result.toString("UTF-8");
//            } catch (IOException ex) {
//                logger.error("所有读取请求体的方式都失败", ex);
//                return null;
//            }
//        }
//    }
//
//    /**
//     * 登录成功
//     * @param req
//     * @param res
//     * @param chain
//     * @param auth
//     * @throws IOException
//     * @throws ServletException
//     */
//    /**
//     * 登录成功
//     */
//    protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain,
//                                            Authentication auth) throws IOException, ServletException {
//        logger.info("=== 进入登录成功处理 ===");
//        SecurityUser user = (SecurityUser) auth.getPrincipal();
//        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername());
//        redisTemplate.opsForValue().set(user.getCurrentUserInfo().getUsername(), user.getPermissionValueList());
//
//        // 设置响应内容
//        res.setContentType("application/json;charset=UTF-8");
//        res.setStatus(HttpServletResponse.SC_OK);
//
//        R result = R.ok().data("token", token);
//        String jsonResponse = new ObjectMapper().writeValueAsString(result);
//
//        // 直接写入响应并完成请求
//        res.getWriter().write(jsonResponse);
//        res.getWriter().flush();
//
//        logger.info("=== 登录成功处理完成，返回token: {} ==="+token);
//    }
//
//    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
//                                              AuthenticationException e) throws IOException, ServletException {
//        logger.error("=== 登录失败: " + e.getMessage() + " ===");
//        ResponseUtil.out(response, R.unAuth());
//    }
//
//}
